/**
 * fshows.com
 * Copyright (C) 2013-2020 All Right Reserved
 */
package com.fshows.leshuapay.sdk.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author zhaoyi
 * @version FileUtil.java, v 0.1 2020-07-27 11:23 zhaoyi
 */
@Slf4j
public class FileUtil {

    public static String downLoadFromUrlNew(String urlStr, String fileName, String savePath) {
        log.info("文件下载，url = {}，fileName={}, savePath = {}", urlStr, fileName, savePath);
        URL url;
        FileOutputStream fos = null;
        InputStream inputStream = null;
        InputStream inputStreamTemp = null;
        try {
            url = new URL(urlStr);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setConnectTimeout(10 * 1000);
            httpURLConnection.setReadTimeout(10 * 1000);
            //防止屏蔽程序抓取而返回403错误
            httpURLConnection
                    .setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            httpURLConnection.connect();
            inputStream = httpURLConnection.getInputStream();
            //文件目录
            File saveDir = new File(savePath);
            //创建文件父级目录
            File parentSaveDir = saveDir.getParentFile();
            if (!parentSaveDir.exists()) {
                parentSaveDir.mkdirs();
            }
            //创建文件目录
            if (!saveDir.exists()) {
                saveDir.mkdir();
            }
            File file = new File(saveDir + File.separator + fileName);
            if (!file.exists()) {
                file.setWritable(true, false);
                file.setExecutable(true, false);
                file.setReadable(true, false);
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int readLength;
            while ((readLength = inputStream.read(buffer)) != -1) {
                fos.write(buffer, 0, readLength);
            }
            fos.flush();

            //判断文件名称
            File fileTemp = new File(saveDir + File.separator + fileName);
            inputStreamTemp = new FileInputStream(fileTemp);
            String fileType = getFileTypeByInputStream(inputStreamTemp);
            if (StringUtils.isBlank(fileType)) {
                log.error("下载文件失败，{}", "文件类型不正确");
                return "";
            }
            /*+"."+fileType*/
            fileTemp.renameTo(new File(saveDir + File.separator + fileName));
            /* + "." + fileType*/
            return fileName;
        } catch (IOException e) {
            log.error("下载文件失败，{}", e.getMessage());
            return "";
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (inputStreamTemp != null) {
                    inputStreamTemp.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getFileTypeByInputStream(InputStream inputStream) {
        try {
            String res = null;
            byte[] b = new byte[3];
            inputStream.read(b, 0, b.length);
            String fileCode = bytesToHexString(b);
            Map<String, String> FILE_TYPE_MAP = fileType();
            Iterator<String> keyIter = FILE_TYPE_MAP.keySet().iterator();
            while (keyIter.hasNext()) {
                String key = keyIter.next();
                //比较前几位是否相同就可以判断文件格式（相同格式文件文件头后面几位会有所变化）
                if (key.toLowerCase().startsWith(fileCode.toLowerCase()) || fileCode.toLowerCase().startsWith(key.toLowerCase())) {
                    res = FILE_TYPE_MAP.get(key);
                    break;
                }
            }
            return res;
        } catch (Exception e) {
            log.error("获取文件类型异常{}", e);
            return "";
        }
    }

    /**
     * 根据文件流判断文件类型
     *
     * @param
     * @return
     */
    public static Map<String, String> fileType() {
        Map<String, String> FILE_TYPE_MAP = new HashMap<>(8);
        //JPEG (jpg)
        FILE_TYPE_MAP.put("ffd8ffe000104a464946", "jpg");
        //PNG (png)
        FILE_TYPE_MAP.put("89504e470d0a1a0a0000", "png");
        //GIF (gif)
        FILE_TYPE_MAP.put("47494638396126026f01", "gif");
        //16色位图(bmp)
        FILE_TYPE_MAP.put("424d228c010000000000", "bmp");
        //24位位图(bmp)
        FILE_TYPE_MAP.put("424d8240090000000000", "bmp");
        //256色位图(bmp)
        FILE_TYPE_MAP.put("424d8e1b030000000000", "bmp");
        return FILE_TYPE_MAP;
    }

    /**
     * 得到文件头
     *
     * @param src
     * @return
     */
    private static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (null == src || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
}
